﻿using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Sqlite;
using System.ComponentModel;
using System.Linq;
using System.Globalization;

namespace 综合同步
{
    public class WRDataBase : DbContext
    {
        DateTime m_time = DateTime.MinValue;
        static object obj = new object();
        static WRDataBase _inst;
        public static WRDataBase instance(){
            string path = Path.GetDirectoryName(LocalServer.GetConfigValue<string>("DataBase"));
            lock(obj)
            {
                if(_inst == null || !File.Exists(Path.Combine(path,DateTime.Now.ToString("yyyyMMdd") + ".db")))
                    _inst = new WRDataBase(DateTime.Now);
                return _inst;
            }
        }
        
        public static WRDataBase[] CreateReadDB(){
            string path = Path.GetDirectoryName(LocalServer.GetConfigValue<string>("DataBase"));
            return new DirectoryInfo(path).GetFiles("*.db",SearchOption.AllDirectories).ToArray<FileInfo>().Select(
                o=>{
                    DateTime time = DateTime.MinValue;
                    DateTime.TryParseExact(Path.GetFileNameWithoutExtension(o.FullName),
                        "yyyyMMdd",CultureInfo.CurrentCulture, DateTimeStyles.None,out time);
                    return time;
                }).Where(o=>o!=DateTime.MinValue).Select(o=>new WRDataBase(o)).ToArray();
        }
        private WRDataBase(DateTime time)
        {
            try
            {
                m_time = time;
                string path = Path.GetDirectoryName(LocalServer.GetConfigValue<string>("DataBase"));
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                if (!File.Exists(Path.Combine(path,m_time.ToString("yyyyMMdd") + ".db")))
                    Database.EnsureCreated();
            }
            catch (Exception) { }
        }
        ~WRDataBase(){ Dispose(); }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string path = Path.GetDirectoryName(LocalServer.GetConfigValue<string>("DataBase"));
            optionsBuilder.UseSqlite("Data Source="+ Path.Combine(path, m_time.ToString("yyyyMMdd") + ".db"));
        }
        #region 字段
        public DbSet<TBArcing> ArcingEntities { get; set; }
        public DbSet<TBTemperature> TemperatureEntities { get; set; }
        public DbSet<TBVideoInfo> VideoInfoEntities { get; set; }
        #endregion
    }
}